package com.example.dictionary.controller;

import com.example.memento.model.DictionaryResult;
import com.example.memento.model.DictionaryStats;
import com.example.memento.model.DownloadTask;
import com.example.memento.model.WordEntry;
import com.example.dictionary.service.DictionaryDownloadService;
import com.example.dictionary.service.DictionaryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 词典REST API控制器
 */
@RestController
@RequestMapping("/api/dictionary")
public class DictionaryController {
    
    private static final Logger log = LoggerFactory.getLogger(DictionaryController.class);
    
    private final DictionaryService dictionaryService;
    private final DictionaryDownloadService downloadService;
    
    public DictionaryController(DictionaryService dictionaryService, 
                              DictionaryDownloadService downloadService) {
        this.dictionaryService = dictionaryService;
        this.downloadService = downloadService;
    }
    
    /**
     * 搜索单词
     */
    @GetMapping("/search")
    public ResponseEntity<List<DictionaryResult>> searchWord(@RequestParam String word) {
        try {
            List<WordEntry> entries = dictionaryService.searchWord(word);
            List<DictionaryResult> results = entries.stream()
                    .map(this::convertToResult)
                    .collect(Collectors.toList());
            
            return ResponseEntity.ok(results);
        } catch (Exception e) {
            System.out.println("搜索单词失败: " + word + ", 错误: " + e.getMessage());
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 模糊搜索单词
     */
    @GetMapping("/search/fuzzy")
    public ResponseEntity<List<DictionaryResult>> searchWordFuzzy(@RequestParam String keyword) {
        try {
            List<WordEntry> entries = dictionaryService.searchWordContaining(keyword);
            List<DictionaryResult> results = entries.stream()
                    .map(this::convertToResult)
                    .collect(Collectors.toList());
            
            return ResponseEntity.ok(results);
        } catch (Exception e) {
            log.error("模糊搜索失败: {}", keyword, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 根据源搜索
     */
    @GetMapping("/search/source")
    public ResponseEntity<List<DictionaryResult>> searchBySource(@RequestParam String source) {
        try {
            List<WordEntry> entries = dictionaryService.searchBySource(source);
            List<DictionaryResult> results = entries.stream()
                    .map(this::convertToResult)
                    .collect(Collectors.toList());
            
            return ResponseEntity.ok(results);
        } catch (Exception e) {
            log.error("根据源搜索失败: {}", source, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取词典统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<DictionaryStats> getStatistics() {
        try {
            DictionaryStats stats = dictionaryService.getStatistics();
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("获取统计信息失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 加载所有词典
     */
    @PostMapping("/load")
    public ResponseEntity<Map<String, String>> loadAllDictionaries() {
        try {
            dictionaryService.loadAllDictionaries();
            return ResponseEntity.ok(Map.of("message", "词典加载任务已启动"));
        } catch (Exception e) {
            log.error("加载词典失败", e);
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 获取下载任务状态
     */
    @GetMapping("/download/tasks")
    public ResponseEntity<List<DownloadTask>> getDownloadTasks() {
        try {
            List<DownloadTask> tasks = downloadService.getAllDownloadTasks();
            return ResponseEntity.ok(tasks);
        } catch (Exception e) {
            log.error("获取下载任务失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取特定下载任务状态
     */
    @GetMapping("/download/tasks/{taskId}")
    public ResponseEntity<DownloadTask> getDownloadTask(@PathVariable String taskId) {
        try {
            return downloadService.getDownloadTask(taskId)
                    .map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            log.error("获取下载任务失败: {}", taskId, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 检查文件是否已下载
     */
    @GetMapping("/download/status/{sourceName}")
    public ResponseEntity<Map<String, Boolean>> checkDownloadStatus(@PathVariable String sourceName) {
        try {
            boolean isDownloaded = downloadService.isFileDownloaded(sourceName);
            return ResponseEntity.ok(Map.of("downloaded", isDownloaded));
        } catch (Exception e) {
            log.error("检查下载状态失败: {}", sourceName, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取已下载的文件列表
     */
    @GetMapping("/download/files")
    public ResponseEntity<List<String>> getDownloadedFiles() {
        try {
            List<java.nio.file.Path> files = downloadService.getDownloadedFiles();
            List<String> fileNames = files.stream()
                    .map(path -> path.getFileName().toString())
                    .collect(Collectors.toList());
            
            return ResponseEntity.ok(fileNames);
        } catch (Exception e) {
            log.error("获取已下载文件列表失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, String>> health() {
        return ResponseEntity.ok(Map.of(
                "status", "UP",
                "service", "Dictionary Service",
                "timestamp", String.valueOf(System.currentTimeMillis())
        ));
    }
    
    /**
     * 将WordEntry转换为DictionaryResult
     */
    private DictionaryResult convertToResult(WordEntry entry) {
        DictionaryResult result = new DictionaryResult();
        result.setWord(entry.getWord());
        result.setPronunciation(entry.getPronunciation());
        result.setTranslation(entry.getTranslation());
        result.setDefinition(entry.getDefinition());
        result.setExample(entry.getExample());
        result.setPartOfSpeech(entry.getPartOfSpeech());
        result.setSource(entry.getSource());
        result.setLanguage(entry.getLanguage());
        result.setTargetLanguage(entry.getTargetLanguage());
        result.setTags(entry.getTags());
        result.setFrequency(entry.getFrequency());
        result.setConfidence(entry.getConfidence());
        
        // 计算相关性分数（简单实现）
        result.setRelevanceScore(calculateRelevanceScore(entry));
        
        return result;
    }
    
    /**
     * 计算相关性分数
     */
    private Double calculateRelevanceScore(WordEntry entry) {
        double score = 0.0;
        
        // 基于频率
        if (entry.getFrequency() != null) {
            score += Math.log(entry.getFrequency() + 1) * 0.3;
        }
        
        // 基于置信度
        if (entry.getConfidence() != null) {
            score += entry.getConfidence() * 0.4;
        }
        
        // 基于是否有例句
        if (entry.getExample() != null && !entry.getExample().isEmpty()) {
            score += 0.2;
        }
        
        // 基于是否有定义
        if (entry.getDefinition() != null && !entry.getDefinition().isEmpty()) {
            score += 0.1;
        }
        
        return Math.min(score, 1.0); // 限制在0-1之间
    }
}
